// 创建birds.js
var express = require('express')
const pool = require("../db/connectionPool"); // 导入连接池
const { TABLE_HISTORY_NAME } = require('../constants/constants')
var getCaiPiaoHistortApi = express.Router()// 创建一个路由实例

function getHistoryData(page, pageNum) {
  return new Promise((resolve, reject) => {
    try {
      if (!pool) {
        reject(new Error('连接池获取失败'))
        return
      }
      // 从连接池中获取数据库的连接对象
      console.log(`开始获取连接`);
      pool.getConnection(function (err, conn) {
        if (err) {
          console.log(`获取连接失败`);
          conn.release()
          reject(err)
        } else {
          // 定义sql查询语句
          const offset = (page - 1) * pageNum;
          const sql = `SELECT * FROM ${TABLE_HISTORY_NAME} LIMIT ?, ?`;
          console.log(`数据库连接成功,offset--->${offset},pageNum--->${pageNum}`);
          // 查询操作
          conn.query(sql, [offset, pageNum], function (err, result) {
            if (err) {
              console.log("数据库查询失败" + err.message);
              conn.release()
              reject(err)
            } else {
              console.log("数据库查询成功，数据长度是---》" + result?.length);
              if (result && result.length > 0) {
                conn.release()
                resolve(result)
              } else {
                conn.release()
                reject(new Error('获取到的数据为空'))
              }
            }
          })
        }

      })
    } catch (err) {
      console.log(`getHistoryData失败--->${err.message}`);
      reject(err)
    }
  })
}

// 中间件功能
getCaiPiaoHistortApi.use(function timeLog(req, res, next) {
  console.log('Time: ', new Date().toLocaleString())
  next()
})
// 访问/getApi
getCaiPiaoHistortApi.get('/', async function (req, res) {
  // 获取参数
  let headers = req.headers ? JSON.stringify(req.headers) : '';
  let params = req.params ? JSON.stringify(req.params) : '';
  let query = req.query ? JSON.stringify(req.query) : '';
  console.log('params :----> ', params)
  console.log('query   :----> ', query)
  console.log('headers   :----> ', headers)

  try {
    let queryObj = JSON.parse(JSON.stringify(req.query))
    if (!queryObj || !queryObj.page || !queryObj.pageNum) {
      res.send("参数错误")
      return
    }
    let selectPage = Number.parseInt(queryObj.page)
    let selectPageNumber = Number.parseInt(queryObj.pageNum)
    if (selectPage < 0 || selectPageNumber < 0) {
      res.send("请设置正确的页码数")
      return
    }
    console.log('selectPage   :----> ', selectPage)
    console.log('selectPageNumber   :----> ', selectPageNumber)
    let result = await getHistoryData(selectPage, selectPageNumber)
    if (!result) {
      res.send("获取历史开奖数据失败")
      return
    }
    let data = {
      header: headers,
      params: params,
      query: query,
      method: req.method,
      url: req.originalUrl,
      code: 200,
      data: result,
      msg: '获取数据成功'
    }
    // res.header("Access-Control-Allow-Origin", "*") 
    // res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE")
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    let resultStr = JSON.stringify(data)
    // console.log('返回结果   :----> ', resultStr)
    res.end(resultStr)
  } catch (err) {
    res.send("请求错误" + err.message)
    return
  }

})





// 访问/getInfo/:id
getCaiPiaoHistortApi.get('/getInfo/:city/:id/query', function (req, res) {
  // 获取参数
  let requestId = req.params.id.toString();
  let city = req.params.city.toString();
  if (requestId === '634' && city === 'hangzhou') {
    res.send('city is :---> ' + city)
  } else {
    res.send("参数错误，你丫的再检查一次")
  }

})

// 访问/getPlus/:id
getCaiPiaoHistortApi.get('/getTest', function (req, res) {
  // 获取参数
  let headers = req.headers ? JSON.stringify(req.headers) : '';
  let params = req.params ? JSON.stringify(req.params) : '';
  let query = req.query ? JSON.stringify(req.query) : '';
  console.log('params :----> ', params)
  console.log('query   :----> ', query)
  console.log('headers   :----> ', headers)
  res.json({
    header: headers,
    params: params,
    query: query,
    method: req.method,
    url: req.originalUrl,
    msg: '服务器回复'
  })

})


module.exports = getCaiPiaoHistortApi
